package com.allwees.bs.task.misc;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Service
public class UpdateTableServiceImpl implements UpdateTableService {

	@Autowired
	private DataSource dataSource;

	private String dbName;

	private JdbcTemplate jdbcTemplate;

	@PostConstruct
	private void init() {
		NamedParameterJdbcDaoSupport jdbcDaoSupport = new NamedParameterJdbcDaoSupport();
		jdbcDaoSupport.setDataSource(dataSource);
		jdbcTemplate = jdbcDaoSupport.getJdbcTemplate();
		dbName = parseDbName();
	}

	@Override
	public List<String> tables() {
		return jdbcTemplate.queryForList("show tables")
						.stream()
						.flatMap(map -> map.entrySet().stream())
						.map(Map.Entry::getValue)
						.map(Object::toString)
						.collect(Collectors.toList());
	}

	@Override
	public List<Map<String,Object>> columnsOfDatetime() {
		String sql = "select table_name,column_name from information_schema.columns where table_schema='%s' and data_type='datetime'";
		return jdbcTemplate.queryForList(String.format(sql, dbName));
	}


	@Override
	public List<Map<String,Object>> columnsOfDatetimeWithPrecision() {
		String sql = "select table_name,column_name,is_nullable,datetime_precision from information_schema.columns where table_schema='%s' and data_type='datetime' and datetime_precision !=0";
		return jdbcTemplate.queryForList(String.format(sql, dbName));
	}


	@Override
	public void update(String sql) {
		jdbcTemplate.execute(sql);
	}

	private String parseDbName() {
		if(!(dataSource instanceof DruidDataSource)) {
			throw new RuntimeException("目前只支持从DruidDataSource获取jdbc信息并建立连接");
		}
		String dbUrl = ((DruidDataSource) dataSource).getUrl();
		if(dbUrl.contains("?")) {
			dbUrl = StringUtils.substringBefore(dbUrl, "?");
		}
		return dbUrl.substring(dbUrl.lastIndexOf("/") + 1);
	}

}
